<?php
/**
 *
 * Created by PhpStorm
 * Date: 2022/9/27
 * Time: 15:53
 * docs:
 */

namespace Buu\Modules\Deployment\Controllers;

use App\Models\DeploymentDetail;
use Doraemon\tools\Log;
use Encore\Admin\Grid;
use Encore\Admin\Form;
use Encore\Admin\Widgets\Tab;
use Hhz\Drone\Gateway;
use App\Library\Common;
use Doraemon\tools\HhzEnv;
use Illuminate\Http\Request;
use App\Models\DeploymentList;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\MessageBag;
use Doraemon\service\DomainConfig;
use Buu\Modules\Deployment\Service\GitLab;
use Illuminate\Database\Eloquent\Collection;
use Encore\Admin\Controllers\AdminController;
use Doraemon\model\DomainConfig\TemplateHost;
use function AlibabaCloud\Client\json;

class IndexController extends AdminController
{
    private const DEPLOY_CONFIG_File = "DroneConfigMap.json";
    public static array $aGolbalConfig = [];
    public static array $aDeployConfig = [];


    public function __construct()
    {
        $dir = __DIR__ . "/Lib/" . self::DEPLOY_CONFIG_File;
        $sConfig = file_get_contents($dir);
        $aDeployConfig = json_decode($sConfig, true, 512, JSON_THROW_ON_ERROR);

        self::$aGolbalConfig = $aDeployConfig['global_config'];
        self::$aDeployConfig = $aDeployConfig['deploy_config'];
    }

    /**
     * title
     *
     * @return string
     */
    protected function title(): string
    {
        return "测试环境部署";
    }

    public function index(Content $content)
    {
        $content->title($this->title())
            ->breadcrumb([
                'text' => $this->title
            ]);
        $tab = new Tab();
        $tab->add('测试环境', $this->grid(DeploymentList::QA), false, 1);
        $tab->add('预发环境', $this->grid(DeploymentList::GRAY), false, 2);
        return $content->body($tab);
    }


    /**
     * 列表构建
     *
     * @return Grid|string
     * @throws \Exception
     */
    protected function grid($iEnv)
    {

        Admin::script($this->delScript());
        Admin::script($this->createAgainScript());
        $grid = new Grid(new DeploymentList());
        $grid->model()->where('status', DeploymentList::STATUS_NORMAL);
        $grid->model()->where('env', $iEnv)->orderBy('updated_at', 'desc');
        $grid->model()->collection(function (Collection $collection) {
            foreach ($collection as $k => $item) {
                //释放时间
                $sDate = date('Y-m-d 21:00:00', strtotime($item->updated_at));
                if($sDate < $item->updated_at ){
                    $sDate = date('Y-m-d 21:00:00', strtotime('+1 day') );
                }
                $sFreeDate = date('Y-m-d 21:00:00', strtotime('-7 day'));

                $item->updated_at = date('Y-m-d H:i:s', strtotime($item->updated_at));
                $item->release_at = $sDate;
                $item->real_status = 1;
                if (time() > strtotime($sDate)) {
                    $item->real_status = 2;
                }
                if ($item->real_status == 2 && $sFreeDate > $item->updated_at) {
                    unset($collection[$k]);
                    continue;
                }

                $sDetail = json_encode($item->detail, JSON_THROW_ON_ERROR);
                $aDetail = json_decode($sDetail, true, 512, JSON_THROW_ON_ERROR);

                $item->branch = $aDetail;
                $item->pod = $aDetail;
                $item->log = $aDetail;
                $item->name_space = DeploymentList::ENV[$item->env] . $item->host;
            }
            // 最后一定要返回集合对象
            return $collection;
        });

        $grid->disableFilter();
        $grid->disableExport();
        $grid->disableBatchActions();
        $grid->disablePagination();
//        $grid->column('id', 'ID');


        $grid->column('host', '环境')->display(function ($host) {
            return DeploymentList::ENV[$this->env] . $host;
        })->label();
        $grid->column('uid', '创建人')->display(function ($userId) {
            return Admin::user()->find($userId)->name;
        });
        $grid->column('desc', '用途');
        $grid->column('branch', '分支')->display(function ($aDetail) {
            $html = '';
            if ($aDetail) {
                foreach ($aDetail as $aInfo) {

                    $aBranch = json_decode($aInfo['branch'], true);
                    if (empty($aBranch)) {
                        continue;
                    }
                    foreach ($aBranch as $sProject => $sBranch) {
                        if (in_array($sProject, ['resource_config_qa', 'resource_config_gray'])) {
                            $sProject = 'resource_config';
                            $sPath = self::$aGolbalConfig[DeploymentList::ENV[$this->env]]['resource_config'];
                        } else {
                            $sPath = self::$aDeployConfig[$aInfo['project']]['git'][$sProject];
                        }

                        $sLabel = $sProject . ':' . $sBranch;
                        $sBadge = 'https://shields.haohaozhu.me/drone/build/' . $sPath . '/' . $sBranch . '?server=https://drone.haohaozhu.me&label=' . $sLabel;
                        $sTabUrl = self::$aGolbalConfig['drone_detail_link'] . $sPath;

                        if ($aInfo['project'] == 'php-all-in-one') {
                            if ($sBranch !== 'master') {
                                $html .= '<div class="span-label" style="margin-bottom: 5px"><span class="label"><a href=' . $sTabUrl . '  target = "_blank" ><img src="' . $sBadge . '"></a></span></div>';
                            }
                        } else {
                            $html .= '<div class="span-label" style="margin-bottom: 5px"><span class="label"><a href=' . $sTabUrl . '  target = "_blank" ><img src="' . $sBadge . '"></a></span></div>';
                        }
                    }
                }
            }
            if (!$html) {
                return '<div class="span-label" style="margin-bottom: 5px"><span class="label label-success"> master </span></div>';
            }
            return $html;
        });
        $grid->column('updated_at', '构建时间');
        $grid->column('release_at', '预计释放时间');
        $grid->column('real_status', '状态')->using(
            [
                2 => '已释放',
                1 => "正常"
            ]
            , '未知')->label([
            2 => 'default',
            1 => 'success',
        ]);

        $grid->column('detail', '部署状态')->display(function ($aDetail) {
            $html = '';
            if (!empty($aDetail)) {
                foreach ($aDetail as $aInfo) {
                    if ($aInfo['deploy_status'] == 1) {
                        $sUrl = 'https://shields.haohaozhu.me/endpoint?url=https://drone-build-endpoint.haohaozhu.me/' . self::$aDeployConfig[$aInfo['project']]['drone_address'] . '/builds/' . $aInfo['link_drone_id'];
                        $html .= '<div class="span-label" style="margin-bottom: 5px"><span class="label"><a href=' . self::$aGolbalConfig['drone_detail_link'] . self::$aDeployConfig[$aInfo['project']]['drone_address'] . '/' . $aInfo['link_drone_id'] . '  target = "_blank"><img src="' . $sUrl . '"></a ></span></div>';


                    }
                }
            }
            return $html;
        })->width(180);

        $grid->column('pod', '容器')->display(function ($aDetail) {
            $html = '';
            if (!empty($aDetail)) {
                foreach ($aDetail as $aInfo) {
                    foreach (self::$aDeployConfig as $key => $aDeploy) {
                        if ($aInfo['project'] == $key) {
                            if ($aDeploy['pod']) {

                                $cluster_id = self::$aGolbalConfig[DeploymentList::ENV[$this->env]]['cluster_id'];
                                $sUrl = str_replace(['{$cluster_id}', '{$namespace}'],
                                    [$cluster_id, $this->name_space], $aDeploy['pod']);

                                $html = '<div class="span-label" style="margin-bottom: 5px"><span class="label label-success"><a style="color: white " href="' . $sUrl . '"  target = "_blank"> pod </a></span></div> ';
                            }
                        }
                    }
                }
            }
            return $html;
        })->width(100);

        $grid->column('log', '日志')->display(function ($aDetail) {
            $html = '';
            if (!empty($aDetail)) {
                foreach ($aDetail as $aInfo) {
                    foreach (self::$aDeployConfig as $key => $aDeploy) {
                        if ($aInfo['project'] == $key) {
                            if ($aDeploy['log']) {

                                $sNamespacePath = self::$aGolbalConfig[DeploymentList::ENV[$this->env]]['namespace_path'];
                                $sNamespace = $this->name_space;

                                foreach ($aDeploy['log'] as $name => $sUrl) {
                                    $sUrl = str_replace(['{$namespace_path}', '{$namespace}'],
                                        [$sNamespacePath, $sNamespace], $sUrl);

                                    $html .= '<div class="span-label" style="margin-bottom: 5px"><span class="label label-success"><a style="color: white " href="' . $sUrl . '"  target = "_blank">' . $name . '</a></span></div> ';
                                }
                            }
                        }
                    }
                }
            }
            return $html;

        })->width(100);

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableDelete();
            $actions->append('<a style="color: red; margin-left: 15px;" class="act-del fa fa-registered" href="javascript:;"  data-id="' . $actions->row->id . '" data-action="online"> 释放 </a>&nbsp;');
            $actions->prepend('<a class="create_again fa fa-repeat" href="javascript:;"  data-id="' . $actions->row->id . '" data-action="online">重新创建 </a>&nbsp;');
        });

        return $grid->render();
    }

    /**
     * 编辑
     */
    public function edit($id, Content $content)
    {
        $form = new Form($aInfo = DeploymentList::find($id));
        $form->tools(function (Form\Tools $tools) {
            // 去掉`列表`按钮
            $tools->disableList();
            // 去掉`删除`按钮
            $tools->disableDelete();
            // 去掉`查看`按钮
            $tools->disableView();
        });
        $form->hidden('e_id')->default($aInfo['id']);
        $form->disableCreatingCheck();
        $form->disableEditingCheck();
        $form->disableViewCheck();

        $aDetail = DeploymentDetail::getInfo(['deploy_id' => $id, 'status' => 1]);
        $aDetailList = [];
        foreach ($aDetail as $aDetailInfo) {
            $aDetailList[$aDetailInfo['project']] = json_decode($aDetailInfo['branch'], true);
        }

        $form->column(1 / 4, function ($form) use ($aInfo, $aDetailList) {
            //从配置里面获取创建的项目
            $form->text('desc', '用途')->default($aInfo['desc']);

            if ($aInfo['env'] == 1) {
                $branch = $aDetailList['php-all-in-one']['resource_config_gray'] ?? 'master';
                $sResourceConfigAds = self::$aGolbalConfig['gray']['resource_config'];
                $form->select('resource_config_gray', 'resource_config')
                    ->options([$branch => $branch])
                    ->default($branch)
                    ->ajax('/admin/Deployment/index/list?name_detail='.$sResourceConfigAds);
            } else {
                $branch = $aDetailList['php-all-in-one']['resource_config_qa'] ?? 'master';
                $sResourceConfigAds = self::$aGolbalConfig['qa']['resource_config'];
                $form->select('resource_config_qa', 'resource_config')
                    ->options([$branch => $branch])
                    ->default($branch)
                    ->ajax('/admin/Deployment/index/list?name_detail='.$sResourceConfigAds);

            }
        });

        //前端 & 服务
        $form->column(1 / 3, function ($form) use ($aDetailList) {
            //从配置里面获取创建的项目
            foreach (self::$aDeployConfig as $key => $aConfig) {
                if ($key == 'php-all-in-one') {
                    continue;
                }
                $iNum = !empty($aDetailList[$key]) ? 1 : 2;
                $form->radio($key . '_choose', $key)
                    ->options([
                        1 => '是',
                        2 => '否'
                    ])->default(2)->when(1, function (Form $form) use ($key, $aDetailList, $aConfig) {
                        $branch = $aDetailList[$key][$key] ?? 'master';
                        $form->select($key, '分支')
                            ->options([$branch => $branch])
                            ->default($branch)
                            ->ajax('/admin/Deployment/index/list?name_detail=' . self::$aDeployConfig[$key]['git'][$key]);
                    })->default($iNum);
            }
        });

        //后端
        $form->column(1 / 3, function ($form) use ($aDetailList) {
            $form->hidden('php-all-in-one_choose', '后端')->value(1);
            //从配置里面获取创建的项目
            foreach (self::$aDeployConfig['php-all-in-one']['git'] as $key => $aConfig) {
                $branch = $aDetailList['php-all-in-one'][$key] ?? 'master';
                $form->select($key, $key)
                    ->options([$branch => $branch])
                    ->default($branch)
                    ->ajax('/admin/Deployment/index/list?' . "name_detail=" . self::$aDeployConfig['php-all-in-one']['git'][$key]);
            }

        });

        $form->setAction('/admin/Deployment/index/saveEdit');
        return $content
            ->breadcrumb(
                ['text' => '列表', 'url' => '/Deployment/index'],
                ['text' => '编辑']
            )
            ->description("编辑")
            ->header(DeploymentList::ENV[$aInfo['env']] . $aInfo['host'] . "-编辑")
            ->body($form->render());
    }


    /**
     * 清除已释放
     */
    public static function Freelist()
    {

        $aList = DeploymentList::getFreeList(['status' => 1], date('Y-m-d 21:00:00', strtotime('-7 day')));
        if (!empty($aList)) {
            DeploymentList::updateDataIN($aList, ['status' => 9]);
            DeploymentDetail::updateDataIN($aList, ['status' => 9]);

        }
    }

    /*
     * 添加表单
     */
    protected function form(): string
    {
        self::Freelist();

        $form = new Form(new DeploymentList());
        $form->disableCreatingCheck();
        $form->disableEditingCheck();
        $form->disableViewCheck();
        $form->column(1 / 4, function ($form) {
            $form->radio('env', '环境')
                ->options([
                    2 => '好好测',
                    1 => '预发',
                ])->when(1, function (Form $form) {
                    $where = [
                        'status' => DeploymentList::STATUS_NORMAL,
                        'env' => 1,
                    ];
                    $aCurrentHost = DeploymentList::getHostList($where);
                    $aHosts = $this->getNumList(10, 1);
                    $aHostList = array_diff($aHosts, $aCurrentHost);
                    reset($aHostList);
                    $first_key = key($aHostList);
                    $form->select('host', '环境域名')->options($aHostList)->default($first_key);

                    $form->text('desc', '用途');
                    $sResourceConfigAds = self::$aGolbalConfig['gray']['resource_config'];
                    $form->select("resource_config_gray", 'resource_config')
                        ->options(["master" => "master"])
                        ->default("master")
                        ->ajax('/admin/Deployment/index/list?name_detail='.$sResourceConfigAds);
                })->when(2, function (Form $form) {

                    $where = [
                        'status' => DeploymentList::STATUS_NORMAL,
                        'env' => 2,
                    ];
                    $aCurrentHost = DeploymentList::getHostList($where);
                    $aHosts = $this->getNumList(10, 1);
                    $aHostList = array_diff($aHosts, $aCurrentHost);
                    reset($aHostList);
                    $first_key = key($aHostList);
                    $form->select('host', '环境域名')->options($aHostList)->default($first_key);


                    $form->text('desc', '用途');

                    $sResourceConfigAds = self::$aGolbalConfig['qa']['resource_config'];


                    $form->select('resource_config_qa', 'resource_config')
                        ->options(["master" => "master"])
                        ->default("master")
                        ->ajax('/admin/Deployment/index/list?name_detail='.$sResourceConfigAds);

                })->default(2);
        });


        $form->column(1 / 3, function ($form) {
            //从配置里面获取创建的项目
            foreach (self::$aDeployConfig as $key => $aConfig) {
                if ($key == 'php-all-in-one') {
                    continue;
                }
                $form->radio($key . '_choose', $key)
                    ->options([
                        1 => '是',
                        2 => '否'
                    ])->default(2)->when(1, function (Form $form) use ($key) {
                        if(self::$aDeployConfig[$key]['domain']){
                            $form->hidden('domain', 'domain')->value(1);
                        }
                        $form->select($key, '分支')
                            ->options(["master" => "master"])
                            ->default("master")
                            ->ajax('/admin/Deployment/index/list?name_detail=' . self::$aDeployConfig[$key]['git'][$key]);
                    })->default(2);
            }
        });
        $form->hidden('php-all-in-one_choose', '后端')->value(1);
        $form->column(1 / 3, function ($form) {
            foreach (self::$aDeployConfig['php-all-in-one']['git'] as $name => $nameDetail) {
                $form->select($name, $name)
                    ->options(["master" => "master"])
                    ->default("master")
                    ->ajax('/admin/Deployment/index/list?' . "name_detail=" . $nameDetail);
            }
        });

        $form->setAction('save');
        return $form->render();
    }

    /**
     * 获取分支
     *
     * @param Request $request
     * @return array
     * @time 2022/9/28 17:55
     * @desc
     */
    public function list(Request $request): array
    {
        $sNameDetail = $request->get('name_detail') ?? '';
        $sSearchBranchName = $request->get('q') ?? '';
        $page = (int)$request->get('page') ?: 1;

        $aList = (new GitLab())->getBranches($sNameDetail, ['search' => $sSearchBranchName, 'page' => $page]);
        $aTemp = [];
        foreach ($aList as $aItem) {
            $aTemp[] = [
                'text' => $aItem['name'],
                'id' => $aItem['name']
            ];
        }
        $url = "/admin/Deployment/index/list?name_detail=" . $sNameDetail . "&q=" . $sSearchBranchName . "&page=";
        $aResList["per_page"] = 20;
        $aResList["current_page"] = $page;
        $aResList["next_page_url"] = $url . ($page + 1);
        $iPrevPage = $page > 1 ? $page - 1 : 1;
        $aResList["prev_page_url"] = $url . $iPrevPage;
        $aResList['data'] = $aTemp;

        if (!$aList) {
            $aResList["next_page_url"] = '';
        }
        return $aResList;
    }

    /**
     * 添加保存
     */
    public function save(Request $request)
    {
        try {
            $aParams = $request->all();
            $rules = [
                "desc" => "required",
                "host" => "required|integer",
            ];
            $msg = Common::validatorRule($rules, $aParams);
            if ($msg !== true) {
                throw new \Exception($msg);
            }

            $aList['uid'] = Admin::user()->id;
            $aList['desc'] = $aParams['desc'];
            $aList['env'] = $aParams['env'];
            $aList['host'] = $aParams['host'];
            $aList['created_at'] = date('Y-m-d H:i:s');
            $sDomian = $aParams['domain'];

            $aWhere = [
                'env' => $aList['env'],
                'host' => $aList['host'],
                'status' => DeploymentList::STATUS_NORMAL,
            ];

            $aInfo = DeploymentList::getFromHost($aWhere);
            if ($aInfo) {
                throw new \Exception("该环境已被占用！");
            }

            //存主表
            $sDeployId = DeploymentList::saveData($aList);

            $target = DeploymentList::ENV[$aList['env']] . $aList['host'];

            $this->addDomain($target, $aList['env'],$sDomian);

            //存详情表
            $aChooseDeploy = array_keys(self::$aDeployConfig);
            foreach ($aChooseDeploy as $aChooseName) {
                $aBranch = [];
                $aProDetail = [
                    'deploy_id' => $sDeployId,
                    'project' => $aChooseName,
                    'branch' => json_encode([], JSON_THROW_ON_ERROR),
                    'deploy_status' => 2,
                    'status' => 1,
                ];
                $sDbDetailId = DeploymentDetail::saveData($aProDetail);
                if (1 == $aParams[$aChooseName . '_choose']) {

                    $aGitList = self::$aDeployConfig[$aChooseName]['git'];
                    foreach ($aGitList as $k => $sGit) {
                        $aBranch[$k] = $aParams[$k];
                        if ($aChooseName == 'php-all-in-one') {
                            if ($aParams['resource_config_qa']) {
                                $aBranch['resource_config_qa'] = $aParams['resource_config_qa'];
                            }
                            if ($aParams['resource_config_gray']) {
                                $aBranch['resource_config_gray'] = $aParams['resource_config_gray'];
                            }
                        }
                    }
                    $target = DeploymentList::ENV[$aList['env']] . $aList['host'];
                    //构建
                    $sDroneDeployBranch = self::$aDeployConfig[$aChooseName]['drone_deploy_branch'];
                    if (HhzEnv::isProduction()) {
                        if ($sDroneDeployBranch) {
                            $sDroneId = $this->drone($target, $aBranch,
                                self::$aDeployConfig[$aChooseName]['drone_address'],
                                $sDroneDeployBranch);
                        } else {
                            $sDroneId = $this->drone($target, [], self::$aDeployConfig[$aChooseName]['drone_address'],
                                $aBranch[$aChooseName]);
                        }
                    } else {
                        $sDroneId = 12;
                    }
                    //更新表
                    DeploymentDetail::updateData(['id' => $sDbDetailId],
                        [
                            'link_drone_id' => $sDroneId,
                            'deploy_status' => 1,
                            'branch' => json_encode($aBranch, JSON_THROW_ON_ERROR)
                        ]);
                }
            }

            $success = new MessageBag([
                'title' => '成功',
            ]);
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->with(compact('error'))->withInput();
        }
        return redirect('/admin/Deployment/index')->with(compact('success'));
    }

    /**
     * 部署无人机
     */
    public function drone(
        string $target,
        array $project = ['doraemon' => 'master', 'biz' => 'master'],
        string $sPromotePath,
        $branch = 'master'
    ) {
        Log::info('部署 :' . $sPromotePath . '--' . $branch . '--' . $target, $project);

        $drone = new Gateway(
            'https://drone.haohaozhu.me/api/',
            'nFIBGyqDaNe0N4iS33ir9SAPg54nVAQ3'
        );
        sleep(1);
        return $drone->Promote($sPromotePath, $target, $project, $branch);
    }

    /**
     * 编辑保存
     */
    public function saveEdit(Request $request)
    {
        try {
            $aParams = $request->all();
            $sDeployId = $aParams['e_id'];
            $aInfo = DeploymentList::getOne($sDeployId);

            //前端和服务部署
            DeploymentDetail::updateData(['deploy_id' => $sDeployId], ['status' => 9]);

            //存详情表
            $aChooseDeploy = array_keys(self::$aDeployConfig);
            foreach ($aChooseDeploy as $aChooseName) {
                $aBranch = [];
                $aProDetail = [
                    'deploy_id' => $sDeployId,
                    'project' => $aChooseName,
                    'branch' => json_encode([], JSON_THROW_ON_ERROR),
                    'deploy_status' => 2,
                    'status' => 1,
                ];
                $sDbDetailId = DeploymentDetail::saveData($aProDetail);
                if (1 == $aParams[$aChooseName . '_choose']) {

                    $aGitList = self::$aDeployConfig[$aChooseName]['git'];
                    foreach ($aGitList as $k => $sGit) {
                        $aBranch[$k] = $aParams[$k];
                        if ($aChooseName == 'php-all-in-one') {
                            if ($aParams['resource_config_qa']) {
                                $aBranch['resource_config_qa'] = $aParams['resource_config_qa'];
                            }
                            if ($aParams['resource_config_gray']) {
                                $aBranch['resource_config_gray'] = $aParams['resource_config_gray'];
                            }
                        }
                    }
                    $target = DeploymentList::ENV[$aInfo['env']] . $aInfo['host'];
                    //构建
                    if (HhzEnv::isProduction()) {
                        $sDroneDeployBranch = self::$aDeployConfig[$aChooseName]['drone_deploy_branch'];
                        if ($sDroneDeployBranch) {
                            $sDroneId = $this->drone($target, $aBranch,
                                self::$aDeployConfig[$aChooseName]['drone_address'],
                                $sDroneDeployBranch);
                        } else {
                            $sDroneId = $this->drone($target, [], self::$aDeployConfig[$aChooseName]['drone_address'],
                                $aBranch[$aChooseName]);
                        }
                    }
                    //更新表
                    DeploymentDetail::updateData(['id' => $sDbDetailId],
                        ['link_drone_id' => $sDroneId, 'deploy_status' => 1, 'branch' => json_encode($aBranch)]);
                }
            }

            //更新list 表数据
            DeploymentList::updateData(['id' => $sDeployId],
                ['desc' => $aParams['desc'], 'status' => 1, 'updated_at' => date('Y-m-d H:i:s')]);

        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->with(compact('error'))->withInput();
        }

        $success = new MessageBag([
            'title' => '成功',
        ]);
        return redirect('/admin/Deployment/index')->with(compact('success'));
    }

    /**
     * 审核
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function del(Request $request): JsonResponse
    {
        try {
            $params = $request->all();
            $id = $params['id'];

            $rule = [
                'id' => 'required|int',
            ];
            $validator_msg = Common::validatorRule($rule, $params);
            if ($validator_msg !== true) {
                throw  new \Exception($validator_msg);
            }

            $info = DeploymentList::getOne($params['id']);
            if (!$info) {
                throw new \Exception('不存在的活动');
            }

            $data['status'] = DeploymentList::STATUS_DEL;
            DeploymentList::saveInfo($id, $data);

            $target = 'del-' . DeploymentList::ENV[$info['env']] . $info['host'];

            $aDetail = DeploymentDetail::getInfo(['deploy_id' => $id, 'deploy_status' => 1, 'status' => 1]);
            foreach ($aDetail as $aInfo) {
                $sDroneDeployBranch = self::$aDeployConfig[$aInfo['project']]['drone_deploy_branch'] ?? $aInfo['project'];
                $sPromotePath = self::$aDeployConfig[$aInfo['project']]['drone_address'];
                if (HhzEnv::isProduction()) {
                    $this->drone($target, [], $sPromotePath, $sDroneDeployBranch);
                }
            }

            DeploymentDetail::updateData(['deploy_id' => $id], ['status' => 9]);

            $success = [
                'title' => '操作成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }

        return response()->json($success);
    }

    /**
     * @return string
     * @time 2022/10/10 13:20
     * @desc
     */
    private function delScript()
    {
        return <<<SCRIPT
        $('.act-del').unbind('click').click(function(){
            var id= $(this).data('id');
            let url = '/admin/Deployment/index/del'
            let params = {id:id}
            swal({
                    title: "确认释放吗？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
                    preConfirm: function() {
                    //ajax
                        $.ajax({
                            method: 'post',
                            url: url,
                            data: params,
                            success: function (e) {
                                if (e.code == 1) {
                                swal({
                                    title: e.title,
                                    type: "success",
                                });
                                    setTimeout(function () {
                                        $.pjax.reload('#pjax-container');
                                    }, 5000);
                                } else {
                                    toastr.error(e.title, null, {
                                        timeOut : 3000
                                    }); 
                                }
                            }
                        });
                    //ajax-end
                    }
            });
        });
       
SCRIPT;
    }

    /**
     * 创建域名
     *
     * @param string $sTarget
     * @param int $iEnv
     * @return bool|int|mixed|string
     * @throws \Exception
     * @time 2022/10/10 14:18
     * @desc
     */
    public function addDomain(string $sTarget, int $iEnv, $sDomian = '')
    {
        $sSiteStr = '.hhzgray.com/';
        if ($iEnv === 2) {
            $sSiteStr = '.hhzqa.com/';
        }

        $iTemplateId = 3;
        if ($iEnv === 1) {
            $iTemplateId = 2;
        }

        $jTempContent = TemplateHost::getByWhere([
            'id' => $iTemplateId,
            'template_status' => TemplateHost::STATUS_NORMAL
        ],
            'content');
        $aList = $jTempContent ? json_decode($jTempContent, true) : [];
        if (!$aList) {
            throw new \Exception('域名模板不存在！');
        }

        foreach ($aList as $k => $v) {
            $aNewList[$k] = '';
        }
        if ($sDomian) {
            foreach (self::$aDeployConfig as $aList){
                if($aList['domain']){
                    $aNewList[$aList['domain']] = 'http://' . $aList['domain'] . '.' . $sTarget . $sSiteStr;
                }
            }
        }

        $aNewList['mh5'] = 'http://m.' . $sTarget . $sSiteStr;
        $aNewList['th5'] = 'http://t.' . $sTarget . $sSiteStr;
        $aNewList['yapi'] = 'http://yapi.' . $sTarget . $sSiteStr;
        $aNewList['api'] = 'http://api.' . $sTarget . $sSiteStr;
        $aNewList['tapi'] = 'http://tapi.' . $sTarget . $sSiteStr;
        $sDoMainName = $sTarget;
        $jDoMainHost = $aNewList;
        return DomainConfig::createOrUpdate($sDoMainName, $jDoMainHost, $iTemplateId);
    }

    /**
     * 重新部署
     *
     * @param Request $request
     * @return JsonResponse
     * @time 2022/10/10 16:50
     * @desc
     */
    public function createAgain(Request $request): JsonResponse
    {

        try {
            $sDeployId = $request->post('id');

            $aInfo = DeploymentList::getOne($sDeployId);
            $aDetail = DeploymentDetail::getInfo(['deploy_id' => $sDeployId, 'status' => 1]);

            if (!$aInfo || !$aDetail) {
                throw new \Exception('项目不存在!');
            }

            foreach ($aDetail as $aDetailInfo) {
                if ($aDetailInfo['deploy_status'] == 1) {
                    $target = DeploymentList::ENV[$aInfo['env']] . $aInfo['host'];

                    $aBranch = json_decode($aDetailInfo['branch'], true);
                    $project = $aDetailInfo['project'];

                    if (HhzEnv::isProduction()) {

                        //构建
                        $sDroneDeployBranch = self::$aDeployConfig[$project]['drone_deploy_branch'];
                        if ($sDroneDeployBranch) {
                            $sDroneId = $this->drone($target, $aBranch,
                                self::$aDeployConfig[$project]['drone_address'],
                                $sDroneDeployBranch);
                        } else {
                            $sDroneId = $this->drone($target, [], self::$aDeployConfig[$project]['drone_address'],
                                $aBranch[$project]);
                        }
                    } else {
                        $sDroneId = 12;
                    }

                    //更新表
                    DeploymentDetail::updateData(['id' => $aDetailInfo['id']], ['link_drone_id' => $sDroneId]);

                }
            }
            //更新list 表数据
            DeploymentList::updateData(['id' => $sDeployId],
                ['uid' => Admin::user()->id, 'updated_at' => date('Y-m-d H:i:s'), 'status' => 1]);

            $success = [
                'title' => '操作成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }


    /**
     * @return string
     * @time 2022/10/10 13:20
     * @desc
     */
    private function createAgainScript()
    {
        return <<<SCRIPT
        $('.create_again').unbind('click').click(function(){
            var id= $(this).data('id');
            let url = '/admin/Deployment/index/createAgain'
            let params = {id:id}
            swal({
                    title: "确认创建吗？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
                    preConfirm: function() {
                    //ajax
                        $.ajax({
                            method: 'post',
                            url: url,
                            data: params,
                            success: function (e) {
                                if (e.code == 1) {
                                swal({
                                    title: e.title,
                                    type: "success",
                                });
                                    setTimeout(function () {
                                        $.pjax.reload('#pjax-container');
                                    }, 1000);
                                } else {
                                    toastr.error(e.title, null, {
                                        timeOut : 3000
                                    }); 
                                }
                            }
                        });
                    //ajax-end
                    }
            });
        });
       
SCRIPT;
    }

    /**
     * 获取数据列表
     *
     * @param $iMax
     * @param $iStart
     * @return array
     * @time 2022/10/19 11:10
     * @desc
     */
    public function getNumList($iMax, $iStart): array
    {
        $aNumList = [];
        for ($i = 1; $i <= $iMax; $i++) {
            if ($i >= $iStart) {
                $aNumList[$i] = $i;
            }
        }
        return $aNumList;
    }
}